﻿using System;
using System.Collections.Generic;
using System.Linq;
using CommandLine;
using SetVersionNumber.VersionStrategies;

namespace SetVersionNumber {

	/// <summary>
	/// This very simple program does one thing:  set the version number
	/// inside a NuGet .nuspec formatted file.
	/// </summary>
	/// <remarks>
	/// The program accepts two parameters:
	/// The first is the name of the file to modify, while the second
	/// is the version number; either and both are optional.
	/// </remarks>
	public static class Program {

		public static int Main( string[] args ) {
			Console.WriteLine("SetVersionNumber v2.1.1");

			// Create our updater to actually do the work
			var updater = new FileVersionUpdater();

			// Parse the command line options
			var options = new Options(updater);
			var parser = new CommandLineParser(new CommandLineParserSettings(false, false, Console.Out));
			if( parser.ParseArguments(args, options)==false )
				return -1;

			// Determine the file to operate on
			IEnumerable<string> fileNames = options.FileNames;
			if( fileNames==null || fileNames.Count()==0 ) {
				// Search for files to update
				fileNames = updater.FindAllUpdatableFiles();

				// If there are still no files to update, we can't proceed
				if( fileNames==null ) {
					Console.WriteLine("Could not determine files to update");
					return -2;
				}//if
			}//if - no file name

			// Determine the naming strategy
			var strategyName = options.StrategyName;
			var versionNumber = options.Version;

			// Tell the explicit version strategy, in case we use it
			if( string.IsNullOrWhiteSpace(versionNumber)==false )
				ExplicitVersionStrategy.UserDefinedVersionNumber = versionNumber;

			// If there is no strategy but the user has specified a version number
			// then use the explicit versioning strategy
			if( string.IsNullOrWhiteSpace(strategyName) && string.IsNullOrWhiteSpace(versionNumber)==false )
				strategyName = ExplicitVersionStrategy.NAME;

			//  Configure the default strategy
			if( string.IsNullOrWhiteSpace(strategyName) )
				strategyName = IncrementRevisionVersionStrategy.NAME;

			// Find the strategy to use
			var strategy = updater.FindStrategyByName(strategyName);
			if( strategy==null ) return -3;

			// Okay, we're ready to process the files
			int numberOfFilesUpdated = updater.UpdateVersionNumbersInFile(strategy, fileNames);

			// Write out a success message
			Console.WriteLine("Successfully upgraded {0} files", numberOfFilesUpdated);
			return 0;
		}

	}//class

}//namespace
